package jokode

import (
	"fmt"
	"os"
	"strings"
	"sync"
)

type RunMode int

const (
	RunModeNone RunMode = iota
	RunModeDev
	RunModeProd
)

func (m RunMode) String() string {
	switch m {
	case RunModeNone:
		return "NONE"
	case RunModeDev:
		return "DEV"
	case RunModeProd:
		return "PROD"
	default:
		return "UNKNOWN"
	}
}

var (
	envRunModeLocker *sync.RWMutex
	envRunMode       RunMode
)

func SetRunMode(mode RunMode) {
	if mode == RunModeNone {
		panic(fmt.Sprintf("can not set run mode to  %s(%d)", RunModeNone, RunModeNone))
	}

	envRunModeLocker.Lock()
	defer envRunModeLocker.Unlock()

	envRunMode = mode
}

func GetRunMode() RunMode {
	envRunModeLocker.RLock()
	defer envRunModeLocker.RUnlock()
	return envRunMode
}

func (m RunMode) IsUnderDev() bool {
	return m == RunModeDev
}

func (m RunMode) IsUnderProd() bool {
	return m == RunModeProd
}

func GetRuntimeDir() string {
	var dirName string

	if dir, err := os.Getwd(); err != nil {
		Errorf("try get runtime dir fail, error info: %v", err)
		return "RunPath"
	} else {
		dirName = dir
	}

	if idx := strings.LastIndexByte(dirName, os.PathSeparator); idx < 0 {
		return dirName
	} else {
		return dirName[idx+1:]
	}
}
